
#include <semaphore.h>

#include <librally.h>

Err rp_sem_init(rp_sem_t *sem, int pshared, unsigned int value)		// We don't need Sem shared between process.
{
	static char fname[] = "rp_sem_init";
	static char msg[] = "fatal error";
	Err err;

	if (sem_init(sem, pshared, value) < 0)	// Non-shared semaphor
	{
		rp_log(LOG_CRITICAL, fname, "Failed to initialize semaphore. Error: %s", strerror(errno));
	}
	
	return err;
}

Err rp_sem_destroy(sem_t  *sem)
{
	static char fname[] = "rp_sem_destroy";
	static char msg[] = "fatal error";
	Err err;

	if (sem_destroy(sem) < 0)	
	{
		rp_log(LOG_CRITICAL, fname, "Failed to destroy semaphore. Error: %s", strerror(errno));
	}
	
	return err;
}

Err rp_sem_post(sem_t *sem)
{
	static char fname[] = "rp_sem_post";
	static char msg[] = "fatal error";
	Err err;

	if (sem_post(sem) < 0)	
	{
		rp_log(LOG_CRITICAL, fname, "Failed to call sem_post(). Error: %s", strerror(errno));
	}
	
	return err;
}

Err rp_sem_wait(sem_t * sem)
{
	static char fname[] = "rp_sem_wait";
	static char msg[] = "fatal error";
	Err err;

	if (sem_wait(sem) < 0)	
	{
		rp_log(LOG_CRITICAL, fname, "Failed to call sem_wait(). Error: %s", strerror(errno));

	}
	
	return err;
}

int rp_sem_trywait(sem_t * sem)
{
	static char fname[] = "rp_sem_trywait";
	static char msg[] = "fatal error";
	Err err;
	
	return sem_trywait(sem);
}

Err rp_sem_getvalue(sem_t * sem, int * val)
{
	static char fname[] = "rp_sem_getvalue";
	static char msg[] = "fatal error";
	Err err;

	if (sem_getvalue(sem, val) < 0)	
	{
		rp_log(LOG_CRITICAL, fname, "Failed to call sem_getvalue(). Error: %s", strerror(errno));

	}
	
	return err;
}

Err rp_sem_setvalue(sem_t *sem, int val)
{
	static char fname[] = "rp_sem_setvalue";
	static char msg[] = "fatal error";
	Err err;

	// TODO:
	
	return err;
}

